package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/mojocn/base64Captcha"
)

var store = base64Captcha.DefaultMemStore

// GenerateCaptcha 生成验证码
func generateCaptcha() (string, string, error) {
	driver := base64Captcha.NewDriverDigit(80, 240, 5, 0.7, 80)
	captcha := base64Captcha.NewCaptcha(driver, store)
	id, b64s, _, err := captcha.Generate()
	return id, b64s, err
}

// VerifyCaptcha 校验验证码
func verifyCaptcha(id, value string) bool {
	return store.Verify(id, value, true)
}

func Captcha() gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.Request.Header.Get("captchaId") == "" || c.Request.Header.Get("answer") == "" {
			//生成验证码
			id, b64s, err := generateCaptcha()
			if err != nil {
				c.JSON(200, gin.H{
					"code": 500,
					"msg":  "验证码生成失败",
				})
				return
			}
			c.JSON(200, gin.H{
				"code": 200,
				"msg":  "验证码生成成功",
				"data": gin.H{
					"id":    id,
					"b64s":  b64s,
					"error": err,
				},
			})
			return
		} else {
			if verifyCaptcha(c.Request.Header.Get("captchaId"), c.Request.Header.Get("answer")) {
				c.Next()
			} else {
				c.JSON(200, gin.H{
					"code": 500,
					"msg":  "验证码错误",
				})
			}
		}
	}
}
